package learn.ch1.forkjoin;

import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.RecursiveTask;

/**
 * @Description todo
 * @Author yusj
 * @Date 2021/12/14
 * @Version 1.0
 */
public class ForkJoin01 extends RecursiveTask<Integer> {

    private Integer[] array;
    private Integer beginIndex=0;
    private Integer endIndex=0;

    public ForkJoin01(Integer[] array, Integer beginIndex, Integer endIndex) {
        this.array = array;
        this.beginIndex = beginIndex;
        this.endIndex = endIndex;
    }

    @Override
    protected Integer compute() {
        if(endIndex-beginIndex>1000){
            //分治
            int midIndex=(endIndex-beginIndex)/2+beginIndex;
            ForkJoin01 join1=new ForkJoin01(array,beginIndex,midIndex);
            ForkJoin01 join2=new ForkJoin01(array,midIndex,endIndex);
            //todo 分治后合并 分治后的结果。其实就是一个二叉树。  注意这里的invokeAll
            invokeAll(join1,join2);
            return join1.join()+join2.join();
        }else{
            int count=0;
            for(int i=beginIndex;i<endIndex;i++){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count+=array[i];
            }
            return count;
        }
    }


    public static void main(String[] args) {

        Integer[] array=new Integer[4000];
        Random random=new Random();
        for(int i=0;i<array.length;i++){
            array[i]=random.nextInt();
        }

        long beginTime1=System.currentTimeMillis();
        int count=0;
        for(int i=0;i<array.length;i++){
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            count+=array[i];
        }
        long endTime1=System.currentTimeMillis();
        System.out.println("1 cost "+(endTime1-beginTime1));
        System.out.println(count);


        ForkJoin01 task=new ForkJoin01(array,0,array.length);
        ForkJoinPool pool=new ForkJoinPool();

        long beginTime=System.currentTimeMillis();
        int ret=pool.invoke(task);
        long endTime=System.currentTimeMillis();
        System.out.println("2 cost "+(endTime-beginTime));
        System.out.println(ret);

    }


}
